import BASE_URL from './url.js'

const baseUrl = BASE_URL //初始路径

// token默认过期时间
var expiredTime = +new Date() + 1800 * 1000

// 不需要登录的接口
const noToken = [
	'/Login/Phone',
	'/Login/Email'
];

const request = (options = {}) => {
	// 判断是否需要登录
	// if (!(noToken.indexOf(options.url) >= 0)) {
	// 	// 如果不需要登录
	// 	// 判断token是否过期，过期强制登出，不过期，正常走下一步
	// 	// var expiredTimes = uni.getStorageSync('expiresIn') || expiredTime;
	// 	var expiredTimes = expiredTime;
	// 	var now = +new Date()
	// 	if (expiredTimes - now < 0) {
	// 		// token失效，重新获取
	// 		uni.reLaunch({
	// 			url: '/pages/login/login',
	// 		});
	// 	} else {
	// 		// token有效，不需要操作
	// 		// 获取用户 token
	// 		let userToken = uni.getStorageSync('Authorization')
	// 		if (!userToken) {
	// 			uni.reLaunch({
	// 				url: '/pages/login/login',
	// 			});
	// 			return false;
	// 		} else {
	// 			// 将 token 放入请求头中
	// 			options.headers['Authorization'] = 'Bearer ' + userToken
	// 		}
	// 	}
	// }

	//自定义请求头
	// options.header = {
	// 		"Content-Type": "application/x-www-form-urlencoded"
	// }

	// 如果调用接口不明确不显示 loading
	// if (!options.hideLoading) {
	// 	uni.showLoading({
	// 		title: '加载中'
	// 	});
	// }
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + options.url || '',
			method: options.type || 'GET',
			data: options.data || {},
			header: options.header || {}
		}).then(data => {
			let [err, res] = data;
			resolve(res);
		}).catch(error => {
			reject(error)
		})
	});
}

const sendUploadFile = (options = {}) => {
	//自定义请求头
	// options.header = {
	// 		"Content-Type": "application/x-www-form-urlencoded"
	// }
	let userToken = uni.getStorageSync('Authorization')
	options.headers['Authorization'] = 'Bearer ' + userToken
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + options.url || '',
			method: options.type || 'POST',
			data: options.data || {},
			header: options.header || {}
		}).then(data => {
			let [err, res] = data;
			resolve(res);
		}).catch(error => {
			reject(error)
		})
	});
}

const get = (url, data, options = {}) => {

	options.type = 'GET';
	options.data = data;
	options.url = url;
	return request(options)
}

const post = (url, data, options = {}) => {
	options.type = 'POST';
	options.data = data;
	options.url = url;
	return request(options)
}


export default {
	request,
	sendUploadFile,
	get,
	post
}
